import { ECSWorld } from "../ECSWorld";
import { ECSEntity } from "./ECSEntity";
import { ECSEntitySet } from "./ECSEntitySet";

export class ECSEntitySetImpl implements ECSEntitySet {

    private entities = new Set<ECSEntity>();

    private entitiesById = new Map<string, ECSEntity>();

    constructor(readonly ecs: ECSWorld) {
        this.ecs = ecs;
    }

    size(): number {
        return this.entities.size;
    }

    has(id: string): boolean {
        return this.entitiesById.has(id);
    }

    get(id: string): ECSEntity {
        const entity = this.entitiesById.get(id);
        if (!entity) {
            throw new Error(`[ECS] not found entity '${id}'`);
        }
        return entity;
    }


    add(): ECSEntity {
        let entity: ECSEntity = new ECSEntity();
        entity.ecs = this.ecs;
        entity.setEnabled(true);
        this.entities.add(entity);
        this.entitiesById.set(entity.id, entity);
        return entity;
    }


    delete(id: string): void;
    delete(entity: ECSEntity): void;
    delete(entity: string | ECSEntity): void {
        if (typeof entity === "string") {
            entity = this.get(entity);
        }
        entity.setEnabled(false);
        entity.ecs = null;
        this.entities.delete(entity);
        this.entitiesById.delete(entity.id);
    }


    clear(): void {
        this.entities.forEach((entity) => this.delete(entity));
    }

}